﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace vwsol_DuHoc.Areas.Administrator.Controllers
{
    public class AdminBaseController : Controller
    {
        [HttpPost]
        public WrappedJsonResult UploadImage(HttpPostedFileBase file)
        {
            try
            {
                /*kiểm tra hình ảnh*/
                if (file == null || file.ContentLength == 0)
                {
                    return new WrappedJsonResult
                    {
                        Data = new
                        {
                            IsValid = false,
                            Level = "Warning",
                            Message = "Chọn hình ảnh!"
                        }
                    };
                }
                string extension = Path.GetExtension(file.FileName);
                extension = extension.ToLower();
                if (!(extension == ".jpg" || extension == ".gif" || extension == ".png"))
                {
                    return new WrappedJsonResult
                    {
                        Data = new
                        {
                            IsValid = false,
                            Level = "Warning",
                            Message = "Hình ảnh không đúng định dạng!"
                        }
                    };
                }
                /*end*/
                string physicalPath = Server.MapPath(Url.Content("~/Resource/Upload"));
                string fileName = String.Format("{0}" + extension, Guid.NewGuid().ToString());
                string imagePath = Path.Combine(physicalPath, fileName);
                file.SaveAs(imagePath);
                return new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = true,
                        Level = "Success",
                        Message = @Url.Content("~/Resource/Upload/" + fileName)
                    }
                };
            }
            catch (Exception ex)
            {
                return new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Level = "Error",
                        Message = ex.Message
                    }
                };
            }
        }
    }

    #region nested class
    public class WrappedJsonResult : JsonResult
	{
		public override void ExecuteResult(ControllerContext context)
		{
			context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");
			base.ExecuteResult(context);
			context.HttpContext.Response.Write("</textarea></body></html>");
			context.HttpContext.Response.ContentType = "text/html";
		}
	}
    #endregion
}
